package com.william.jdbcplus.core.ds;

import com.alibaba.druid.pool.DruidDataSource;
import com.william.jdbcplus.core.toolkit.StringUtil;
import lombok.Getter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Logger;

/**
 * 动态数据源路由
 *
 * @author william
 */
@Getter
public abstract class AbstractRoutingDataSource implements DataSource, InitializingBean {
    private Map<String, DruidDataSource> targetDataSources;

    private DruidDataSource defaultTargetDataSource;

    protected final Log logger = LogFactory.getLog(getClass());

    public AbstractRoutingDataSource() {
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    /**
     * Setting a login timeout is not supported.
     */
    @Override
    public void setLoginTimeout(int timeout) throws SQLException {
        throw new UnsupportedOperationException("setLoginTimeout");
    }

    /**
     * LogWriter methods are not supported.
     */
    @Override
    public PrintWriter getLogWriter() {
        throw new UnsupportedOperationException("getLogWriter");
    }

    /**
     * LogWriter methods are not supported.
     */
    @Override
    public void setLogWriter(PrintWriter pw) throws SQLException {
        throw new UnsupportedOperationException("setLogWriter");
    }

    @Override
    public Logger getParentLogger() {
        return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    }


    public void setTargetDataSources(Map<String, DruidDataSource> targetDataSources) {
        this.targetDataSources = targetDataSources;
    }

    public void setDefaultTargetDataSource(DruidDataSource defaultTargetDataSource) {
        this.defaultTargetDataSource = defaultTargetDataSource;
    }

    @Override
    public void afterPropertiesSet() {
        if (this.defaultTargetDataSource == null) {
            throw new IllegalArgumentException("Default DataSource router not initialized");
        }
        if (this.targetDataSources == null) {
            throw new IllegalArgumentException("Property 'targetDataSources' is required");
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        return this.determineTargetDataSource().getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return this.determineTargetDataSource().getConnection(username, password);
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return iface.isInstance(this) ? (T) this : this.determineTargetDataSource().unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return iface.isInstance(this) || this.determineTargetDataSource().isWrapperFor(iface);
    }

    /**
     * 检索当前目标数据源。
     * 调用determineCurrentLookupKey获取key,在targetDataSources中进行查找，是否要会回退，使用默认数据源。
     * 如果找不到数据源就抛出IllegalStateException异常。
     */
    protected DataSource determineTargetDataSource() {
        Assert.notNull(this.defaultTargetDataSource, "Default dataSource router not initialized");
        DataSource dataSource = null;
        String lookupKey = this.determineCurrentLookupKey();
        if (StringUtil.isNotBlank(lookupKey)) {
            if (this.targetDataSources.containsKey(lookupKey)) {
                dataSource = this.targetDataSources.get(lookupKey);
            }
        } else {
            dataSource = this.defaultTargetDataSource;
        }

        if (dataSource == null) {
            throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
        } else {
            return dataSource;
        }
    }

    @Nullable
    protected abstract String determineCurrentLookupKey();
}
